/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import { computed, defineComponent, h, PropType, ref } from 'vue';
import { useControlController, useNamespace } from '@ibiz-template/vue3-util';
import { IDEDataView } from '@ibiz/model-core';
import { ControlVO, IControlProvider } from '@ibiz-template/runtime';
import { CheckinTabCardController } from './checkin-tab-card.controller';
import './checkin-tab-card.scss';

export const CheckinTabCard = defineComponent({
  name: 'IBizCheckinTabCard',
  props: {
    /**
     * @description 数据视图（卡片）模型数据
     */
    modelData: { type: Object as PropType<IDEDataView>, required: true },
    /**
     * @description 应用上下文对象
     */
    context: { type: Object as PropType<IContext>, required: true },
    /**
     * @description 视图参数对象
     * @default {}
     */
    params: { type: Object as PropType<IParams>, default: () => ({}) },
    /**
     * @description 部件适配器
     */
    provider: { type: Object as PropType<IControlProvider> },
    /**
     * @description 部件行数据默认激活模式，值为0:不激活，值为1：单击激活，值为2：双击激活
     */
    mdctrlActiveMode: { type: Number, default: undefined },
    /**
     * @description 是否单选
     */
    singleSelect: { type: Boolean, default: undefined },
    /**
     * @description 是否是简单模式，即直接传入数据，不加载数据
     */
    isSimple: { type: Boolean, required: false },
    /**
     * @description 简单模式下传入的数据
     */
    data: { type: Array<IData>, required: false },
    /**
     * @description 是否默认加载数据
     * @default true
     */
    loadDefault: { type: Boolean, default: true },
  },
  setup() {
    const c = useControlController(
      (...args) => new CheckinTabCardController(...args),
    );
    const ns = useNamespace('checkin-tab-card');

    const classNames = computed(() => {
      return [ns.is('enable-page', c.model.enablePagingBar === true)];
    });

    const curIndex = ref(0);

    const handleClick = (data: ControlVO) => {
      c.onRowClick(data as any);
    };

    /**
     * 绘制加载更多
     *
     */
    const renderLoadMore = () => {
      return Object.is(c.state.total, c.state.items.length) ? null : (
        <div onClick={() => c.loadMore()} class={ns.e('load-more')}>
          更多
        </div>
      );
    };

    const beforeClick = (data: ControlVO) => {
      const index = c.state.items.findIndex(
        (item: IData) => item.srfkey === data.srfkey,
      );
      curIndex.value = index;
      handleClick(data as any);
    };

    /**
     * 绘制默认项
     *
     * @param {IData} data
     */
    const renderDefaultItem = (item: ControlVO) => {
      const findIndex = c.state.selectedData.findIndex((data: IData) => {
        return data.srfkey === item.srfkey;
      });
      const itemClass = [ns.b('item'), ns.is('active', findIndex !== -1)];
      return (
        <div
          class={itemClass}
          key={item.srfkey}
          onClick={() => beforeClick(item)}
        >
          {(c as any).layoutPanelProvider
            ? h((c as any).layoutPanelProvider.component, {
                props: {
                  modelData: c.model,
                  context: c.context,
                  params: c.params,
                  inputData: item,
                },
              })
            : [
                <span class={ns.e('text')}>{item.srfmajortext}</span>,
                <span class={ns.e('key')}>:{item.srfkey}</span>,
              ]}
        </div>
      );
    };

    /**
     * 绘制所有项
     *
     * @return {*}
     */
    const renderItems = () => {
      let tempitems = [];
      if (!curIndex.value || curIndex.value < 3) {
        tempitems.push(...c.state.items.slice(0, 5));
      } else {
        tempitems = c.state.items.slice(curIndex.value - 3, curIndex.value + 2);
      }
      const listTags = tempitems.map((item: any) => {
        return renderDefaultItem(item);
      });
      if (listTags.length < 5) {
        return [listTags, renderLoadMore()];
      }
      return listTags;
    };

    const onPrevClick = () => {
      if (curIndex.value && curIndex.value > 0) {
        curIndex.value -= 1;
        const select = c.state.items[curIndex.value];
        handleClick(select as any);
      }
    };
    const onNextClick = (e: MouseEvent) => {
      if (
        (curIndex.value || curIndex.value === 0) &&
        curIndex.value < c.state.items.length - 1
      ) {
        curIndex.value += 1;
        const select = c.state.items[curIndex.value];
        handleClick(select as any);
      } else if (
        curIndex.value === c.state.items.length - 1 &&
        !Object.is(c.state.total, c.state.items.length)
      ) {
        c.loadMore();
      } else if (!curIndex.value) {
        curIndex.value = 0;
        onNextClick(e);
      }
    };

    const renderTabCard = () => {
      return (
        <div class={ns.b()}>
          <div class={ns.e('total')}>共{c.state.total}条数据</div>
          <div
            class={[ns.e('left'), ns.is('disabled', curIndex.value === 0)]}
            onClick={onPrevClick}
          >
            <ion-icon name='chevron-back-outline'></ion-icon>
          </div>
          <div class={ns.e('items')}>{renderItems()}</div>
          <div
            class={[
              ns.e('right'),
              ns.is('disabled', curIndex.value === c.state.items.length - 1),
            ]}
            onClick={onNextClick}
          >
            <ion-icon name='chevron-forward-outline'></ion-icon>
          </div>
        </div>
      );
    };

    return {
      c,
      ns,
      classNames,
      renderTabCard,
    };
  },
  render() {
    return (
      <iBizControlNavigation controller={this.c}>
        <iBizControlBase controller={this.c}>
          {this.renderTabCard()}
        </iBizControlBase>
      </iBizControlNavigation>
    );
  },
});
